package com.xiyang.operater.config.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Collection;


/**
 * @author xiyang.ycj
 * @since Jul 01, 2019 11:14:10 AM
 */
@Component
public class LoginAuthenticationProvider implements AuthenticationProvider {

    private static final Logger log = LoggerFactory.getLogger(CustomFilterSecurityInterceptor.class);

    private  CustomUserDetailsService userDetailsService;

    public LoginAuthenticationProvider() {
        log.info("**************LoginAuthenticationProvider  loading... ***********************");
    }

    @Autowired
    public LoginAuthenticationProvider(CustomUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }


    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(4);
    }

    /**
     * 身份验证
     *
     * AuthenticationManager的实现类ProviderManager的authenticate调用
     *
     * @param authentication 身份验证请求对象
     * @return 返回一个完全经过身份验证的对象，包括凭据（密码）。
     * @throws AuthenticationException 如果失败引发authenticationException.
     */

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        /* http请求的账户密码 */

        String username = authentication.getName();
        String password = (String) authentication.getCredentials();

       /* 数据库根据用户名查询 */

        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        log.info("[http请求的账户密码]：{}/{}",username,password);
        log.info("[数据库查询的账户密码：{}/{}]",userDetails.getUsername(),userDetails.getPassword());

        if(!passwordEncoder().matches(password,userDetails.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }

        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        log.info("[设置authorities]：{}",authorities);

        return new UsernamePasswordAuthenticationToken(userDetails,password,authorities);
    }


    /**
     * 是否支持处理当前authentication对象
     * @param authentication
     * @return true
     */

    @Override
    public boolean supports(Class<?> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }
}

